﻿using System;

namespace VincentUtil.Ntp
{
    public class NtpSendMessage : NtpMessage
    {
        public NtpSendMessage(DateTime originTime, DateTime transmitTime) : base(originTime, transmitTime)
        {
        }

        public NtpSendMessage() : base(DateTime.MinValue, DateTime.MinValue)
        {
        }

        public override byte[] BuildNTPBytes()
        {
            byte[] ntpData = base.BuildNTPBytes();
            ntpData[0] = 0x1B; // LI = 0, Version = 3 (IPv4 only), Mode = 3 (Client)
            return ntpData;
        }

        public static bool TryResolve(byte[] ntpData, out NtpSendMessage message)
        {
            message = new NtpSendMessage();
            if (ntpData.Length < 48 || ntpData[0] != 0x1B) return false;
            if (!NtpUtil.TryResolveNtpTime(ntpData, _originTimeIndex, out DateTime origionTime))
                return false;
            if (!NtpUtil.TryResolveNtpTime(ntpData, _transmitTimeIndex, out DateTime transmitTime))
                return false;
            message = new NtpSendMessage(origionTime, transmitTime);
            return true;
        }

    }
}
